using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using CRM.Models.Email;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace CRM.Anyleads;

/// <summary>
/// 邮箱有效性验证
/// <see cref="https://www.mail-verifier.com/home/api.php">邮箱验证接口</see>
/// </summary>
public class MailVerifierClient
{
    private readonly IOptions<MailVerifierConfig> _option;
    private readonly ILogger<MailVerifierClient> _logger;

    public MailVerifierClient(IOptions<MailVerifierConfig> option, ILogger<MailVerifierClient> logger)
    {
        _option = option;
        _logger = logger;
    }

    public async Task<EmailVerifyState> VerifyEmailState(string email)
    {
        var uri =
            $"https://api.mail-verifier.xyz/?cmd=verify&key={_option.Value.Key}&email={email}";
        using var httpClient = new HttpClient();
        var res = await httpClient.GetFromJsonAsync<VerifyResponse>(uri);
        
        _logger.LogInformation("验证邮箱{Email}, 请求链接: {Url}, 状态码:{Code},剩余: {Remain}, 描述: {Msg}, ", email, uri, res.Code, res.Credits, res.Msg);
        
        return res switch
        {
            { Code: 1 } => EmailVerifyState.Valid,
            { Code: 0 or -1 } => EmailVerifyState.Invalid,
            { Code: <= -2 and >= -6 } => EmailVerifyState.NeedReverify,
            _ => LogError(res),
        };

        EmailVerifyState LogError(VerifyResponse response)
        {
            _logger.LogInformation("{Email}: {Msg}", email, response.Msg);
            return EmailVerifyState.Invalid;
        }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="Email"></param>
    /// <param name="Code">
    /// 1	有效	邮箱地址有效
    /// 0	无效	邮箱地址无效
    /// -1	格式错误	并非正确的邮箱格式(不扣次数)
    /// -2	网络错误	链接失败请重试(不扣次数)
    /// -3	余额不足	剩余次数用完了,充值可以解决(不扣次数)
    /// -4	KEY错误	请求KEY不存在(不扣次数)
    /// -5	未验证出来	无法确定此电子邮件的状态。因为目标邮局服务器没有响应我们的请求。(不扣次数)
    /// -6	超出并发限制	一分钟不要验证超过2000个邮箱，稍后再试。(不扣次数)
    /// </param>
    /// <param name="Msg"></param>
    /// <param name="Credits"></param>
    private record VerifyResponse(string Email, int Code, string Msg, int Credits);
}


public class MailVerifierConfig
{
    public string Key { get; set; }
}